//
//  KVPlaceHolderTextView.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/7/28.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

class KVPlaceHolderTextView: UITextView {
    ///设置站位字符
    var placeHolderText: String? {
        didSet {
            self.placeHolderLabel.text = placeHolderText
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
     super.init(frame: frame, textContainer: textContainer)
        self.backgroundColor = UIColor.cyanColor() 
       //设置站位图
        setPlaceHolderLabel()
        //设置默认属性.
        self.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        self.alwaysBounceHorizontal = true
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "TextViewTextDidChangeNotification", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func TextViewTextDidChangeNotification() {
        print("changeBegin")
        if self.hasText() {
            self.placeHolderLabel.hidden = true
        } else {
            self.placeHolderLabel.hidden = false
        }
    }
    private func setPlaceHolderLabel() {
        //添加子控件
        addSubview(placeHolderLabel)
        //切换自动布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        //设置约束
        self.addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        self.addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 4))
        self
        
    }
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "没有什么是我不能hold住的"
        label.textColor = UIColor.lightGrayColor()
      
        return label
    }()
}
